/*
 * Copyright 2007-2009 Thomas Krause (thomas@berlin-reloaded.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gidoo.cms.admin.addins;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.extensions.ajax.markup.html.form.upload.UploadProgressBar;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.request.target.resource.ResourceStreamRequestTarget;
import org.apache.wicket.util.resource.FileResourceStream;
import org.gidoo.cms.GidooCMS;
import org.gidoo.cms.admin.AdminPage;
import org.gidoo.cms.jcr.BackupManager;
import org.gidoo.cms.login.GidooCMSSession;
import org.gidoo.wickettools.MessageBox;
import org.gidoo.wickettools.IMessageBoxResultReceiver;
import org.gidoo.wickettools.MessageBox.MessageBoxResult;

/**
 *
 * @author <a href="mailto:thomas@berlin-reloaded.de">Thomas Krause</a>
 */
public class BackupPanel extends AddInPanel
{

  private Form formImport;
  private Form formExport;
  private FileUploadField fileImport;
  private Button btImport;
  private Button btExport;
  private AdminPage adminPage;
  private File lastFileUploaded;

  public BackupPanel(String id, AdminPage adminPage)
  {
    super(id);
    this.adminPage = adminPage;

    lastFileUploaded = null;

    formImport = new Form("formImport");

    formImport.setMultiPart(true);
    
    fileImport = new FileUploadField("fileImport");
    fileImport.setModel(new Model<FileUpload>());
    formImport.add(fileImport);
    btImport = new Button("btImport")
    {

      @Override
      public void onSubmit()
      {
        importCMS();
      }
    };
    btImport.setModel(new ResourceModel("load"));
    formImport.add(btImport);

    formImport.add(new UploadProgressBar("uploadProgress", formImport));
    add(formImport);

    formExport = new Form("formExport");
    btExport = new Button("btExport")
    {

      @Override
      public void onSubmit()
      {
        Date backupTime = new Date();
        File f = BackupManager.exportCMS((GidooCMSSession) getSession());
        if(f != null)
        {
          DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HHmmss");

          // return as request (file)
          RequestCycle.get().setRequestTarget(
            new ResourceStreamRequestTarget(
            new FileResourceStream(f)
            {

              @Override
              public String getContentType()
              {
                return "application/zip";
              }
            }, "backupCMS_" + df.format(backupTime).replaceAll(" ", "_") + ".zip"));
        }
      }
    };
    btExport.setModel(new ResourceModel("exportnow"));
    formExport.add(btExport);

    add(formExport);
  }

  private void importCMS()
  {
    // print warning
    MessageBox msg = new MessageBox(getString("importwarningtitle"), getString("importwarning"),
      true, MessageBox.MessageBoxButtons.YES_NO, adminPage,
      new IMessageBoxResultReceiver()
      {

        public void receiveMessageBoxResult(MessageBoxResult result)
        {
          if(result == MessageBoxResult.YES)
          {
            if(lastFileUploaded != null)
            {
              if(BackupManager.importCMSFromFile(lastFileUploaded, (GidooCMSSession) getSession()))
              {
                // logout since our user might not exist any longer
                ((GidooCMSSession) getSession()).signOut();
                GidooCMS cms = (GidooCMS) getApplication();
                setResponsePage(cms.CMS_CONFIGURATION.getCMSMainPage());
              }
            }
            else
            {
              error(getString("nullupload"));
            }
          }
        }
      });

    FileUpload up = fileImport.getFileUpload();
    if(up != null)
    {
      try
      {
        lastFileUploaded = up.writeToTempFile();
        setResponsePage(msg);
      }
      catch(IOException ex)
      {
        error(getString("ioerror"));
        Logger.getLogger(BackupPanel.class.getName()).log(Level.SEVERE, null, ex);
      }

    }
    else
    {
      error(getString("nofile"));
    }

  }
}
